package com.changzhi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.changzhi.common.constans.RedisConstans;
import com.changzhi.common.constants.RedisConstants;
import com.changzhi.ldyl.model.User;
import com.changzhi.mapper.UserMapper;
import com.changzhi.service.UserService;
import com.changzhi.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author Alfred
 * @since 2019-10-21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public User getUser(String userId) {
		User user = redisUtil.get(RedisConstans.USER + userId);
		if (user == null) {
			QueryWrapper<User> wrapper = new QueryWrapper<>();
			wrapper.lambda().eq(User::getUserId, userId).last("limit 1");
			user = baseMapper.selectOne(wrapper);
		}
		return user;
	}

	@Override
	public User getUserByAccountId(Integer accountId) {
		User user = redisUtil.get(RedisConstans.USER + accountId);
		if (user == null) {
			LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(User::getAccountId, accountId).last("limit 1");
			user = baseMapper.selectOne(wrapper);
			redisUtil.set(RedisConstans.USER + RedisConstans.ACTIVITY_USER, user, RedisConstans.ONE_DAY);
			return user;
		}
		return user;
	}

	@Override
	public User updateUser(User param) {
		baseMapper.update(param, new UpdateWrapper<User>().eq(User.USER_ID, param.getUserId()));
		redisUtil.del(RedisConstants.USER + param.getUserId());
		return getUser(param.getUserId());
	}

}
